import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:yysk_app/env/env.dart';
import 'package:yysk_app/utils/dialog_widget.dart';
import 'package:yysk_app/utils/helper.dart';
import 'package:yysk_app/utils/js_tool.dart';
import 'package:yysk_app/utils/upgrade_notice_dialog.dart';
import 'package:yysk_app/widget/button_widget.dart';
import 'package:oktoast/oktoast.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:url_launcher/url_launcher.dart';

bool get isWeb => kIsWeb;
Future<AppVersion> fetchVersionInfo() async {
  // if(isWeb==true){
  //   return null;
  // }
  // 创建Dio实例
  final dio = Dio();

  try {
    // 发起GET请求
    final response = await dio.get(
      Env.envConfig.envVersionUrl,
      options: Options(
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
        },
      ),
    );
    String responseString = '''$response''';
    // 修复JSON字符串
    String fixedJson = fixJsonString(responseString);
    // 解析为Map
    Map<String, dynamic> jsonMap = jsonDecode(fixedJson);
    return AppVersion.fromJson(jsonMap);
  } on DioException catch (e) {
    // 使用DioException捕获dio错误
    throw Exception('Dio error: ${e.message}');
  } catch (e) {
    throw Exception('Unexpected error: $e');
  }
}

class AppVersion {
  bool? maintenance;
  String? version;
  String? desc;
  String? downloadUrl;
  String? newVersion;
  bool? isForceUpgrade;

  AppVersion({
    this.maintenance,
    this.version,
    this.desc,
    this.downloadUrl,
    this.newVersion,
    this.isForceUpgrade,
  });

  AppVersion.fromJson(Map<String, dynamic> json) {
    maintenance = json["maintenance"];
    version = json["version"];
    desc = json["desc"];
    downloadUrl = json["downloadUrl"];
    newVersion = json["newVersion"];
    isForceUpgrade = json["isForceUpgrade"];
  }

  static List<AppVersion> fromList(List<Map<String, dynamic>> list) {
    return list.map(AppVersion.fromJson).toList();
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> _data = <String, dynamic>{};
    _data["maintenance"] = maintenance;
    _data["version"] = version;
    _data["desc"] = desc;
    _data["downloadUrl"] = downloadUrl;
    _data["newVersion"] = newVersion;
    _data["isForceUpgrade"] = isForceUpgrade;
    return _data;
  }
}

String fixJsonString(String str) {
  // 匹配键：以空白开头，然后是一个单词字符，直到冒号
  // 注意：要避免匹配到值中的内容
  // 我们使用一个正则表达式来匹配键：单词字符（可能包含空格？但这里键没有空格）后跟冒号，并且前面是逗号或大括号
  // 但是，这个字符串的开头也可能有空格
  // 所以，我们匹配：在{或逗号后面，可能有空格，然后捕获键（由字母、数字、下划线组成的字符串），然后是一个冒号
  // 注意：这个对象字面量中，键是简单的标识符，所以我们可以这样匹配
  RegExp exp = RegExp(r'([{,]\s*)([a-zA-Z_][a-zA-Z0-9_]*)\s*:');
  String fixed = str.replaceAllMapped(exp, (Match m) {
    // m[1] 是前面的逗号或大括号加上空格
    // m[2] 是键
    return '${m[1]}"${m[2]}":';
  });

  // 但是，开头可能没有匹配到，所以单独处理开头的键
  // 检查第一个键：如果开头是'{'后跟空格和键，则没有匹配到
  if (fixed.startsWith('{')) {
    // 匹配第一个键
    RegExp firstKey = RegExp(r'^{\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*:');
    fixed = fixed.replaceFirstMapped(firstKey, (Match m) {
      return '{ "${m[1]}":';
    });
  }
  return fixed;
}

// ignore: non_constant_identifier_names
Future<bool> chech_updata({
  required AppVersion res,
  required BuildContext context,
}) async {
  // return true;
  PackageInfo packageInfo = await PackageInfo.fromPlatform();
  String appName = packageInfo.appName;
  String packageName = packageInfo.packageName;
  String version = packageInfo.version; // 获取版本号（如：1.0.0）
  String buildNumber = packageInfo.buildNumber; // 获取构建号（如：1）
  consoleLog('appName===${appName}');
  consoleLog('packageName===${packageName}');
  consoleLog('version===${version}');
  consoleLog('buildNumber===${buildNumber}');
  consoleLog('res===${res.newVersion}');
  consoleLog('res===${res.downloadUrl}');
  consoleLog('res.maintenance===${res.maintenance}');
  consoleLog('res.isForceUpgrade===${res.isForceUpgrade}');
  if (res.maintenance == true) {
    showConfirmDialog(
      context: context,
      fontSize: 16,
      closeButton: false,
          needClose: false,
      message: '服务器正在维护中',
      messages: ['维护中...'],
      type: 'service_maintenance',
      actions: [],
    );
    return false;
  }

  int updataVersion = int.parse((version.replaceAll('.', '')));
  int updataNewversion = int.parse(res.newVersion!.replaceAll('.', ''));
  if (updataVersion < updataNewversion && !kIsWeb) {
    showConfirmDialog(
      context: context,
      fontSize: 16,
      needClose: false,
      closeButton: res.isForceUpgrade == true ? false : true,
      message: '发现新版本',
      type: 'new_version',
      messages: ['${res.desc}'],
      actions: [
        ActionModel(
          width: 204,
          label: '立即更新',  
          onPressed: () {
            launchUrl(Uri.parse("${res.downloadUrl}"));
            return;
          },
        ),
      ],
    );
    // UpgradeNoticeDialog.show(
    //   context,
    //   title: "发现新版本",
    //   content: "新版本：${res.newVersion} \n${res.desc}",
    //   isForceUpgrade: res.isForceUpgrade!,
    //   onUpgrade: () {
    //     launchUrl(Uri.parse("${res.downloadUrl}"));
    //   },
    //   onCancel: () {
    //     // 取消逻辑
    //   },
    //   btmTxt: '立即更新',
    // );
    return false;
  } else {
    return true;
  }
}
